package com.hdax.dm.controller;

import com.hdax.dm.common.exception.user.UserLoginException;
import com.hdax.dm.dto.CommonResponse;
import com.hdax.dm.dto.DtoUtil;
import com.hdax.dm.dto.user.TokenDto;
import com.hdax.dm.service.UserLoginService;
import com.hdax.dm.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 注册账号发送验证码
     * @return
     */
    @PostMapping(path = "/code")
    public CommonResponse code(@RequestBody Map<String,String> params){
        userLoginService.code(params.get("phone"));
        return DtoUtil.returnSuccess("验证码发送成功!",null);
    }

    /**
     * 注册账号
     * @return
     */
    @PostMapping(path = "/register")
    public CommonResponse register(@RequestBody Map<String,String> params){
        boolean b = userLoginService.register(params);
        return DtoUtil.returnSuccess("",b==true?"注册成功！":"注册失败！");
    }

    /**
     * 短信登陆发送验证码
     * @return
     */
    @PostMapping(path = "/msg")
    public CommonResponse msg(@RequestBody Map<String,String> params){
        userLoginService.msg(params.get("phone"));
        return DtoUtil.returnSuccess("验证码发送成功!",null);
    }

    /**
     * 短信验证码登录
     * @return
     */
    @PostMapping(path = "/msg/login")
    public CommonResponse msgLogin(@RequestBody Map<String,String> params, HttpServletRequest request) throws UserLoginException{
        //获取用户输入
        String phone = params.get("phone");
        String inputCode = params.get("vcode");
        String userAgent = request.getHeader("User-Agent");
        TokenDto tokenDto = userLoginService.msgLogin(inputCode,phone,userAgent);
        return DtoUtil.returnSuccess("",tokenDto);
    }

    /**
     * 账号密码登录
     * @param userVo
     * @return
     */
    @PostMapping(path = "/login")
    public CommonResponse<Object[]> login(@RequestBody UserVo userVo,HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        TokenDto tokenDto = userLoginService.login(userVo, userAgent);
        return DtoUtil.returnSuccess("",tokenDto);
    }

    @ExceptionHandler(value = {UserLoginException.class})           //加这个异常提示
    public CommonResponse exceptionHandler(UserLoginException userLoginException){
//        return DtoUtil.returnFail(userLoginException.getErrorMsg(),userLoginException.getErrorCode());
        return DtoUtil.returnFail(userLoginException);
    }

}
